/**
 * Copyright (C) 2015 AgileCentury, Inc. All Rights Reserved.
 */

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

/**
 * AES加密、解密工具类.
 * @author v_liangshuhui
 * @version 1.0
 * @since 2015年6月11日
 */
public final class Aes {

    /**
     * AES加密位数.
     */
    private static final int AES_BYTE = 128;
    /**
     * 进制.
     */
    private static final int RADIX = 16;
    /**
     * 16进制11.
     */
    private static final int TRUE_INT = 0xFF;
    /**
     * 加密、解密密钥.
     */
    private static final String STR_KEY = "dbkey";
    /**
     * 代码规范.
     */
    private Aes() {
    }

    /**
     * 加密.
     * 
     * @param content
     *            需要加密的内容
     * @return 加密後的16进制串
     */
    public static String encrypt(String content) {
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        Cipher cipher;
        byte[] result;
        try {
            cipher = Cipher.getInstance("AES");
            byte[] byteContent;
            byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, genKey());
            result = cipher.doFinal(byteContent);
            return parseByte2HexStr(result); // 加密
        } catch (IllegalBlockSizeException | BadPaddingException e) {
//            log.error(e);
        } catch (InvalidKeyException e) {
//            log.error(e);
        } catch (UnsupportedEncodingException e) {
//            log.error(e);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
//            log.error(e);
        }
        return content;
    }
    /** 
     * 解密 .
     *  
     * @param content 
     *            待解密内容 
     * @return 解密后的串
     */
    public static String decrypt(String content) {
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        try {
            byte[] decryptFrom = parseHexStr2Byte(content);
            Cipher cipher = Cipher.getInstance("AES"); // 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, genKey()); // 初始化
            byte[] result = cipher.doFinal(decryptFrom);
            return new String(result, "UTF-8"); // 加密
        } catch (InvalidKeyException | IllegalBlockSizeException | NoSuchAlgorithmException
                | NoSuchPaddingException | BadPaddingException | NumberFormatException
                | UnsupportedEncodingException e) {
//            log.error(e);
        }
        return content;
    }

    /**
     * 根据密钥获得 SecretKeySpec.
     * 
     * @return 生成密钥
     */
    private static SecretKeySpec genKey() {
        byte[] enCodeFormat = { 0 };
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(STR_KEY.getBytes());
            kgen.init(AES_BYTE, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            enCodeFormat = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
//            log.error(e);
        }
        return new SecretKeySpec(enCodeFormat, "AES");
    }

    /**
     * 将二进制转换成16进制.
     * 
     * @param buf 
     * @return 2进制转16进制
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & TRUE_INT);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制 .
     * 
     * @param hexStr 
     * @return 16进制转换二进制
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), RADIX);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), RADIX);
            result[i] = (byte) (high * RADIX + low);
        }
        return result;
    }
}
